package com.gitee.cashzhang27.test.boot.functional.handler;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.servlet.function.ServerResponse.ok;


import com.gitee.cashzhang27.test.boot.functional.biz.PersonBiz;
import com.gitee.cashzhang27.test.boot.functional.entity.Person;
import java.util.List;
import java.util.Objects;
import lombok.AllArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;

/**
 * Person 处理类.
 *
 * @author Cash Zhang
 * @version v1.0 2020/09/15 16:08
 * @since v1.0
 */
@Component
@AllArgsConstructor
public class PersonHandler {

  private final PersonBiz personBiz;

  public @NonNull
  ServerResponse listPeople(@NonNull ServerRequest request) {
    List<Person> people = this.personBiz.listPeople();
    return ok().contentType(APPLICATION_JSON).body(people);
  }

  public @NonNull
  ServerResponse createPerson(@NonNull ServerRequest request) throws Exception {
    Person person = request.body(Person.class);
    this.personBiz.createPerson(person);
    return ServerResponse.status(HttpStatus.CREATED).build();
  }


  public @NonNull
  ServerResponse createPersons(@NonNull ServerRequest request) throws Exception {
    List<Person> people = request.body(new ParameterizedTypeReference<List<Person>>() {
    });
    this.personBiz.createPersons(people);
    return ServerResponse.status(HttpStatus.CREATED).build();
  }


  public boolean hasPerson(ServerRequest request) {
    String personId = request.pathVariable("id");
    Person person = this.personBiz.getPerson(personId);
    return Objects.isNull(person);
  }

}
